<!DOCTYPE html>
<html>
<head>
    <title>基于Promise模式</title>
    <meta charset="utf-8"/>
    <script>
        function searchTwitter(term) {

            var url, xhr, results, def;
            url = 'http://search.twitter.com/search.json?rpp=100&q=' + term;
            def = new dojo.Deferred();
            xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);

            xhr.onload = function (e) {
                if (this.status === 200) {
                    results = JSON.parse(this.responseText);
                    def.resolve(results);
                }
            };

            xhr.onerror = function (e) {
                def.reject(e);
            };

            xhr.send();
            return def;
        }

        dojo.ready(function () {
            var container = dojo.byId('container');
            searchTwitter('#IE10').then(function (data) {
                data.results.forEach(function (tweet) {
                    dojo.create('li', {
                        innerHTML: tweet.text
                    }, container);
                });
            });
        });

        //////////////////////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////////////////////////////////////////

        var deferred = dojo.xhrGet({
            url: "search.json",
            handleAs: "json"
        });

        deferred.then(function (data) {
            /* handle results */
        }, function (error) {
            /* handle error */
        })

        //////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////Dojo还引入了dojo.DeferredList,支持开发人员同时处理多个dojo.Deferred对象//////////////////////////////////////////////////////////////////////////

        dojo.require("dojo.DeferredList");
        dojo.ready(function () {
            var container, def1, def2, defs;
            container = dojo.byId('container');
            def1 = searchTwitter('#IE10');
            def2 = searchTwitter('#IE9');

            defs = new dojo.DeferredList([def1, def2]);

            defs.then(function (data) {
                // Handle exceptions
                if (!results[0][0] || !results[1][0]) {
                    dojo.create("li", {
                        innerHTML: 'an error occurred'
                    }, container);
                    return;
                }
                var totalResults = concatResults(data[0][1].results, data[1][1].results);

                totalResults.forEach(function (tweet) {
                    dojo.create("li", {
                        innerHTML: tweet.text
                    }, container);
                });
            });
        });
    </script>
</head>
<body>

</body>
</html>